package cn.lg.soar.mvc.config;

import cn.lg.soar.common.util.IpUtil;
import jakarta.servlet.*;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;

import java.io.IOException;

/**
 * @author luguoxiang
 * 开源项目：https://gitee.com/lgx1992/lg-soar 求star！请给我star！请帮我点个star！
 */
@Configuration
@ConditionalOnProperty(value = "lg.mvc.enabled-access-log", havingValue = "true")
public class AccessLogConfig {

    @Bean
    public FilterRegistrationBean<Filter> registrationFilter() {
        FilterRegistrationBean<Filter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new AccessLogFilter());
        registration.addUrlPatterns("/*");
        registration.setName("AccessLogFilter");
        registration.setOrder(Ordered.HIGHEST_PRECEDENCE + 100);
        return registration;
    }


    @Slf4j(topic = "access")
    public static class AccessLogFilter implements Filter {

        @Override
        public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
            long start = System.nanoTime();
            filterChain.doFilter(servletRequest, servletResponse);
            HttpServletRequest request = (HttpServletRequest) servletRequest;
            HttpServletResponse response = (HttpServletResponse) servletResponse;
            log.info(
                    "{}\t{}\t{}\t{}",
                    IpUtil.getRemoteIp(request),
                    request.getServletPath(),
                    response.getStatus(),
                    (System.nanoTime() - start)
            );
        }

    }

}
